<template>
  <van-cell-group inset>
    <van-field
        v-model="entrust.consigneeName"
        label="收货人姓名"
        placeholder="请输入收货人姓名"
    />
    <van-field
        v-model="entrust.consigneePhone"
        label="收货人号码"
        placeholder="请输入收货人号码"
    />
    <van-field
        v-model="entrust.shipperName"
        label="发货人姓名"
        placeholder="请输入发货人姓名"
    />
    <van-field
        v-model="entrust.shipperPhone"
        label="发货人号码"
        placeholder="请输入发货人号码"
    />

    <van-cell
        is-link
        @click="()=>{show = !show}"
        name="地区"
    >
      {{ area }}
    </van-cell>
    <van-popup v-model:show="show" position="bottom">
      <van-area title="选择地区" :area-list="areaList" :columns-placeholder="['请选择', '请选择', '请选择']" @confirm="onConfirm"
                @cancel="()=>{show = !show}"/>
    </van-popup>

    <van-field
        v-model="entrust.postalCode"
        label="邮政编码"
        placeholder="请输入编码"
        maxlength="6"
    />

    <van-field
        v-model="entrust.detailAdd"
        label="详细地址"
        placeholder="请输入街道"
        rows="5"
        type="textarea"
    />

  </van-cell-group>
  <div style="margin: 16px;">
    <van-button round block type="primary" @click="onSubmit">
      提交
    </van-button>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import {areaList} from '@vant/area-data'
import {Toast} from "vant";
import {addEntrustInfo} from "../api/request";
import route from "../config/route";
import {entrustInfo, currentUser} from "../config/globalConfig";

const entrust = ref({
  area: [],
  token: currentUser.token,
  ...entrustInfo
})

const area = ref("请选择地区 ")
let show = ref(false)

const postal_code = ref()

// 页面挂载之后 对已有的值进行初始化
onMounted(() => {
  entrust.value.shipperName = currentUser.userName
  entrust.value.shipperPhone = currentUser.phone
})

const onSubmit = async (value) => {
  Toast("提交了")
  let res = await addEntrustInfo(entrust.value)
  res = res.data
  if (res.statusCode !== 0) {
    Toast(res.message + res.description)
  } else {
    Toast('订单提交成功!')
    await route.push('/user')
  }
}

const onConfirm = (values) => {
  let value = "请选择地区: "
  for (let i = 0; i < values.length; i++) {
    if (values[i].code === '') {
      Toast('请选择完先~')
      return
    }
    entrust.value.area[i] = values[i]
    value += values[i].name + " "
  }
  entrust.value.postalCode = values[2].code
  entrust.value.province = values[0].name
  entrust.value.city = values[1].name
  entrust.value.county = values[2].name
  area.value = value
  show.value = false
}

</script>

<style scoped>

</style>